package com.ykl.base.jpa;

import lombok.extern.slf4j.Slf4j;
import org.hibernate.query.internal.NativeQueryImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.List;

@Component
@Slf4j
public class ExecSqlComp {

    @Autowired
    private EntityManager entityManager;

    public <T> List<T> exec(String sql, Class<T> outClz, Object ... args){
        Query nativeQuery = entityManager.createNativeQuery(sql);
        nativeQuery.unwrap(NativeQueryImpl.class).setResultTransformer(new DefineResultTransformer<>(outClz));
        if(args!=null){
            for(int i=0;i<args.length;i++){
                nativeQuery.setParameter(i+1, args[i]);
            }
        }
        return (List<T>)nativeQuery.getResultList();
    }

}
